var xcommander = {};

$(function() {
	$("#tabs").tabs();
	if(!window.FileReader) {
		$("#tabs-1 > fieldset").remove();
	}
});

$(document).ready(function() {
	var template = null;

	xcommander.lib = new XCommanderStub();
	xcommander.xcommand = new XCommanderXCommandStub();
	xcommander.lib.xhr.send({
		'url' : 'xcommander://templates/xcommand.html',
		'type' : 'text'
	}, init);

	xcommander.lib.storage.getItem("parser_default_lang", function(value) {
		$("#parser_lang").val(value);
	});
	function init(data) {
		template = data.response;
		var storageKeys;
		var file;

		xcommander.xcommand.getAll(function(commandList) {
			sortCommands(commandList);
			for(i in commandList) {
				displayXCommand(commandList[i]);
			}
		});

		$("#parser_lang").change(function(event) {
			var lang = this.value;
			xcommander.lib.storage.setItem("parser_default_lang", lang, function() {

			});
		});

		$("#file").change(function(event) {
			file = event.target.files[0];
			if(this.value.match(/(xcmd$|js$)/)) {
				$("button.upload").removeAttr("disabled");
			} else {
				$("button.upload").attr({
					disabled : 'disabled'
				});
			}
		});

		$("button.upload").click(function() {
			var reader = new FileReader();
			reader.onload = function(event) {
				xcommander.xcommand.validate(event.target.result, function(response) {
					if(response.type == "valid") {
						displayXCommand(response);
					} else {
						alert("Ungültiges XCommand! { Error: " + response.error + " }");
					}
				});
			}
			reader.readAsText(file);
		});
	}

	function sortCommands(commandList) {
		commandList.sort(function(a, b) {
			return new Date(a.xcommand.date).getTime() - new Date(b.xcommand.date).getTime();
		});
	}

	function displayXCommand(data) {
		var key = data.key;
		var xcommand = data.xcommand;
		tmp = $(replacePlaceholders(template, xcommand));
		if(!xcommand.buildIn) {
			if(xcommand.meta.hasOwnProperty("update")) {
				checkUpdate(xcommand, tmp, key);
			}
			tmp.attr({
				id : key
			});
			tmp.find("button").val(key);
			tmp.find("input[type=checkbox]").attr({
				value : key,
				checked : xcommand.enabled
			});

			$(tmp).find("button").click(function() {
				var key = $(this).val()
				xcommander.lib.storage.getJSONItem(key, function(xcommand) {
					if(confirm("XCommand: \"" + xcommand.meta.name + "\" wirklich deinstallieren?")) {
						xcommander.lib.storage.removeItem(key, function(xcommand) {
							$(document).find("fieldset[id='" + key + "']").remove();
						});
					}
				});
			});

			$(tmp).find("input[type=checkbox]").click(function() {
				var key = $(this).val()
				var state = $(this).is(':checked');
				xcommander.lib.storage.getJSONItem(key, function(xcommand) {
					xcommand.enabled = state;
					xcommander.lib.storage.setJSONItem(key, xcommand);
				});
			});
		} else {
			tmp.find("button").remove();
			tmp.find("input[type=checkbox]").remove();
		}
		$('#xcommands').prepend(tmp);
	}

	function checkUpdate(xcommand, tmp, key) {
		xcommander.lib.xhr.send({
			'url' : xcommand.meta.update,
			'type' : 'json',
			'headers' : {
				'Cache-Control' : 'no-cache'
			}
		}, function(update) {
			if(xcommand.meta.version < update.response.xcommand.version) {
				tmp.find("small").append("</br><a a href=\"javascript:void(0)\" rel=\"" + update.response.xcommand.url + "\" id=\"update\" value=\"" + key + "\">Update verfügbar!</a>");

				tmp.find("#update").click(function() {
					if(confirm("XCommand: \"" + xcommand.meta.name + "\" aktualisieren?")) {
						var url = $(this).attr("rel");
						var key = $(this).attr("value");
						xcommander.lib.xhr.send({
							'url' : url,
							'type' : 'text',
							'headers' : {
								'Cache-Control' : 'no-cache'
							}
						}, function(data) {
							xcommander.xcommand.validate(data.response, function(response) {
								if(response.type == "valid") {
									displayXCommand(response);
									removeXCommand(key);
								} else {
									alert("Ungültiges XCommand! { Error: " + response.error + " }");
								}
							});
						});
					}
				});
			}

		});
	}

	function removeXCommand(key) {
		xcommander.lib.storage.getJSONItem(key, function(xcommand) {
			xcommander.lib.storage.removeItem(key, function(xcommand) {
				$(document).find("fieldset[id='" + key + "']").remove();
			});
		});
	}

	function replacePlaceholders(template, xcommand) {
		var tmp = template.replace("{$icon}", xcommand.meta.icon);
		tmp = tmp.replace("{$name}", xcommand.meta.name);
		tmp = tmp.replace("{$discription}", xcommand.meta.description);
		if(xcommand.meta.author.email) {
			tmp = tmp.replace("{$author}", "<a href=\"mailto:" + xcommand.meta.author.email + "\">" + xcommand.meta.author.name + "</a>");
		} else {
			tmp = tmp.replace("{$author}", xcommand.meta.author.name);
		}
		if(xcommand.meta.homepage) {
			tmp = tmp.replace("{$homepage}", "| <a href=\"" + xcommand.meta.homepage + "\">" + xcommand.meta.homepage + "</a>");
		} else {
			tmp = tmp.replace("{$homepage}", "");
		}
		tmp = tmp.replace("{$date}", xcommand.date);
		if(xcommand.meta.license) {
			tmp = tmp.replace("{$license}", xcommand.meta.license);
		}
		tmp = tmp.replace("{$version}", xcommand.meta.version);
		return tmp;
	}

});
